package org.geek.common.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.geek.common.entity.ExtTree;
import org.geek.common.entity.Menu;

/**
 * 菜单类1.1
 * 
 */
public class TreeUtil {

	private List<Menu> list;
	private Menu root;

	public TreeUtil(List<Menu> list,int menuId) {
		this.list = list;
		Menu menu = new Menu();
		menu.setId(menuId);
		this.root = menu;
	}

	/**
	 * 组合json
	 * 
	 * @param list
	 * @param node
	 */
	private ExtTree getNodeJson(List<Menu> list, Menu node) {
		ExtTree tree = new ExtTree();
		tree.setId(node.getId());
		tree.setText(node.getName());
		tree.setIconCls(node.getIconCss());
		tree.setChildren(new ArrayList<ExtTree>());
		if (list == null) {
			// 防止没有权限菜单时
			return tree;
		}
		if (hasChild(list, node)) {
			List<ExtTree> lt = new ArrayList<ExtTree>();
			tree.setUrl("");
			tree.setLeaf(false);
			List<Menu> childList = getChildList(list, node);
			Iterator<Menu> it = childList.iterator();
			while (it.hasNext()) {
				Menu Menus = (Menu) it.next();
				// 递归
				lt.add(getNodeJson(list, Menus));
			}
			tree.setChildren(lt);
		} else {
			tree.setUrl(node.getUrl());
			tree.setLeaf(true);
		}

		return tree;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<Menu> list, Menu node) {
		return getChildList(list, node).size() > 0 ? true : false;
	}

	/**
	 * 得到子节点列表
	 */
	private List<Menu> getChildList(List<Menu> list, Menu Menus) {
		List<Menu> li = new ArrayList<Menu>();
		Iterator<Menu> it = list.iterator();
		while (it.hasNext()) {
			Menu temp = (Menu) it.next();
			if (temp.getParentId() == Menus.getId()) {
				li.add(temp);
			}
		}
		return li;
	}
	
	public ExtTree getTreeJson() {
		return this.getNodeJson(this.list, this.root);
	}
}
